package com.zjcode.cdcer.utils;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.chinatechstar.component.commons.exception.ServiceException;
import org.apache.commons.collections.CollectionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yanghaolin
 * @date 2022/7/25
 * @apiNote EasyExcel工具类处理
 */
public class ExcelUtil {

    public static void exportExcel(List<String> headList, List<LinkedHashMap<String, Object>> dataList, String sheetName, HttpServletResponse response)
            throws IOException {
        ServletOutputStream servletOutputStream = null;
        try {
            servletOutputStream = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = new String((sheetName + new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes(), StandardCharsets.UTF_8);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            ExcelWriter writer = new ExcelWriter(servletOutputStream, ExcelTypeEnum.XLSX, true);
            Sheet sheet = new Sheet(1, 0);
            sheet.setSheetName(sheetName);

            Table table = new Table(1);
            List<List<String>> head = new ArrayList<>();
            if (!CollectionUtils.isEmpty(headList)) headList.forEach(headName -> head.add(Arrays.asList(headName)));
            table.setHead(head);

            List<List<String>> data = new ArrayList<>();
            if (!CollectionUtils.isEmpty(dataList)) dataList.forEach(map -> {
                List<String> list = new ArrayList<>();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    Object value = entry.getValue();
                    list.add(value == null ? null : value.toString());
                }
                data.add(list);
            });

            writer.write0(data, sheet, table);
            writer.finish();
            servletOutputStream.flush();
        } catch (IOException e) {
            throw new ServiceException(e.toString());
        } finally {
            if (servletOutputStream != null) servletOutputStream.close();
        }
    }
}
